import { loginToken } from './api'
import { store } from '../store'
import { setToken, setNickname } from '../store/slices/userSlice'

let timerId: number | null = null
let refreshing = false

const TENANT_ID = (import.meta as any).env?.VITE_TENANT_ID || '000000'
const INTERVAL_MS = 10 * 60 * 1000

export function startRefreshLoop() {
  if (typeof window === 'undefined') return
  if (timerId) return
  const run = async () => {
    if (refreshing) return
    refreshing = true
    try {
      const raw = window.localStorage?.getItem('authInfo')
      const parsed = raw ? JSON.parse(raw) : null
      const refreshToken = parsed?.refreshToken
      if (!refreshToken) {
        stopRefreshLoop()
        return
      }
      const res: any = await loginToken({
        tenantId: TENANT_ID,
        refreshToken,
        // 一些网关要求携带 grantType
        // @ts-expect-error 允许后端忽略无关字段
        grantType: 'refreshToken',
      }).catch(() => null)
      if (!res) return
      // 更新缓存与 redux token
      try {
        window.localStorage?.setItem('authInfo', JSON.stringify(res))
      } catch {}
      const token = res?.accessToken
      const nickname = res?.userName || res?.account
      if (token) {
        store.dispatch(setToken(token))
        if (nickname) store.dispatch(setNickname(nickname))
      }
    } catch (e) {
      // 刷新失败不打断用户，仅在严重情况下可考虑清理登录态
      // stopRefreshLoop()
    } finally {
      refreshing = false
    }
  }
  // 立即触发一次刷新（可选）
  // void run()
  timerId = window.setInterval(run, INTERVAL_MS)
}

export function stopRefreshLoop() {
  if (typeof window === 'undefined') return
  if (timerId) {
    window.clearInterval(timerId)
    timerId = null
  }
}
